package com.scyshkj.university.wechat.wanxiao;

import com.scyshkj.university.wechat.SessionKeys;
import com.scyshkj.university.wechat.utils.JacksonUtil;
import com.scyshkj.university.wechat.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

/**
 * Created by 唐旭 on 2016/11/20.
 */
@Repository
public class WanxiaoAccessTokenRepositoryImpl implements WanxiaoAccessTokenRepository {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WanxiaoProperties wanxiaoProperties;

    @Override
    public WanxiaoAccessToken getAvailableToken(String code) {
        if (!hasAvailable()) {
            WanxiaoAccessTokenRequest request = new WanxiaoAccessTokenRequest(code, wanxiaoProperties);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<String> httpEntity = new HttpEntity<>(request.toUrlString(), headers);
            String accessTokenAsString = restTemplate.postForEntity(wanxiaoProperties.getAccessTokenUrl(), httpEntity, String.class).getBody();
            WanxiaoAccessToken accessToken = JacksonUtil.readValue(accessTokenAsString, WanxiaoAccessToken.class);
            setToken(accessToken);
            return accessToken;
        }
        return getToken();
    }

    private boolean hasAvailable() {
        return getToken() != null && !getToken().expire();
    }

    @Override
    public WanxiaoAccessToken getToken() {
        return (WanxiaoAccessToken) SessionUtils.getAttribute(SessionKeys.WANXIAO_ACCESS_TOKEN);
    }

    public void setToken(WanxiaoAccessToken token) {
        SessionUtils.setAttribute(SessionKeys.WANXIAO_ACCESS_TOKEN, token);
    }
}
